package com.googlecode.zh.wicket.mask;

import com.googlecode.wicket.jquery.ui.JQueryBehavior;
import com.googlecode.wicket.jquery.ui.Options;
import org.apache.wicket.Component;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.apache.wicket.request.resource.ResourceReference;

/**
 * Mask behavior, to mask input. Use "alt" attribute on input fields to mask
 *
 * @author Golyo
 *
 */
public class MaskBehavior extends JQueryBehavior {

    private static final long serialVersionUID = 7638190814181397L;
    private static final ResourceReference INSTANCE = new PackageResourceReference(MaskBehavior.class, "jquery.ui.mask.js");
    private static final String METHOD = "mask";
    private static final String SELECTOR = "input[alt]";

    /**
     * Constructor
     */
    public MaskBehavior() {
        super(SELECTOR, METHOD);
        setOption("clearEmpty ", false);
    }

    /**
     * Constructor
     */
    public MaskBehavior(Options opts) {
        super(SELECTOR, METHOD, opts);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void renderHead(Component component, IHeaderResponse response) {
        super.renderHead(component, response);
        response.render(JavaScriptHeaderItem.forReference(INSTANCE));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String $() {
        String optParams = options.toString();
        optParams = optParams.substring(1, optParams.length() - 1);
        return String.format("$(function() { $(\"%s\").each(function() { var $this = $(this); var mask = $this.attr(\"alt\"); if (mask) { $this.%s({'mask':mask, %s}); } }); });", selector, method, optParams);
    }
}
